<template>
  <div class="gantt-container">
    <!-- 新增：将控制区和图例区放在同一行的容器  search-clear-->
    <div class="header-container">
      <!-- 控制区域 -->
      <div class="controls">
        <div class="equipment-filter">
          <label>设备类型:</label>
          <select v-model="equipmentFilter">
            <option value="all">全部</option>
            <option value="半">半</option>
            <option value="全">全</option>
          </select>
        </div>
        <div class="product-code-filter">
          <label>产品代码:</label>
          <input 
            type="text" 
            v-model="productCodeFilter"
            @input="handleProductCodeFilter"
            placeholder="输入产品代码(多个用逗号分隔)"
            class="filter-input"
          >
          <button @click="clearProductCodeFilter" class="search-clear">
            <i class="fas fa-times-circle"></i>
          </button>
        </div>
        
        
        <div class="search-group">
        <div class="search-item">
          <label>订单号:</label>
          <input 
            type="text" 
            v-model="orderCodeFilter"
            @input="debouncedHandleFilter"
            placeholder="输入完整或部分订单号"
            class="search-input"
          >
          <button @click="clearOrderCodeFilter" class="search-clear">
            <i class="fas fa-times-circle"></i>
          </button>
        </div>

        <!-- <div class="search-item">
          <label>产品代码查询:</label>
          <input 
            type="text" 
            v-model="productCodeFilter"
            @input="debouncedHandleFilter"
            placeholder="输入产品代码(多个用逗号分隔)"
            class="search-input"
          >
          <button @click="clearProductCodeFilter" class="search-clear">
            <i class="fas fa-times-circle"></i>
          </button>
        </div> -->
        <button class="toggle-weight-btn" @click="toggleSingleWeight">
          <i :class="showSingleWeight ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
          {{ showSingleWeight ? '隐藏单重' : '显示单重' }}
        </button>
      </div>
      </div>
      
      <!-- 图例区域 - 添加点击事件 -->
      <div class="legend">
        <!-- 新增订单数量统计 -->
        <div class="legend-count">
          <span class="count-badge">{{ filteredOrdersCount }}</span>
          当前订单数量
        </div>
        <div 
          v-for="(process, index) in processes" 
          :key="index" 
          class="legend-item"
          @click="toggleProcessVisibility(process.key)"
          :class="{ 'legend-hidden': !process.visible }"
        >
          <div class="legend-color" :style="{ backgroundColor: process.color }"></div>
          <span>{{ process.name }}</span>
        </div>
        <div class="legend-item">
          <div class="legend-color" style="background: repeating-linear-gradient(45deg, #fff8e1, #fff8e1 10px, #ffecb3 10px, #ffecb3 20px);"></div>
          <span>今天</span>
        </div>
      </div>
    </div> <!-- 结束 header-container -->

    
    <!-- 甘特图表格容器 -->
    <div 
      class="gantt-table-container"
      ref="ganttContainer"
      @mousedown="startDrag"
      @mousemove="doDrag"
      @mouseup="stopDrag"
      @mouseleave="stopDrag"
    >
      <table class="gantt-table">
        <thead>
          <tr>
            <th class="order-header " >订单号</th>
            <th class="info-header frozen-header" style="width: 70px; text-align: center">产品代码</th>
            <th class="info-header frozen-header" style="width: 70px;">毛坯尺寸</th>
            <th class="info-header frozen-header" style="width: 70px;">首批日期</th>
            <th class="info-header frozen-header" style="width: 70px;">计划数量</th>
            <th v-if="showSingleWeight" class="info-header frozen-header" style="width: 70px;">产品单重</th>
            <th class="info-header frozen-header" style="width: 70px;">订单总重</th>
            <th class="info-header frozen-header" style="width: 70px;">设备类型</th>
            
            <th 
              v-for="(date) in dateRange" 
              :key="date.getTime()"
              class="date-header frozen-header"
              :class="{ 'today-header': isToday(date) }"
              style="min-width: 70px; width: 70px;"
            >
              {{ formatDate(date) }}
              <div style="font-size: 0.7rem; font-weight: normal;">{{ getDayOfWeek(date) }}</div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="order in filteredOrders" :key="order.id">
            <td class="order-cell" @click="openEditDialog(order)">
              {{ order.id }}
              <span class="edit-icon"><i class="fas fa-edit"></i></span>
            </td>
            
            <td class="info-cell" style="width: 70px; text-align: center;">{{ order.productCode }}</td>
            <td class="info-cell" style="width: 70px; text-align: center;">{{ order.blankSize }}</td>
            <td class="info-cell" style="width: 70px; text-align: center;">{{ order.date_first_batch }}</td>
            <td class="info-cell" style="width: 70px; text-align: center;">{{ order.planQuantity }}</td>
            <td v-if="showSingleWeight" class="info-cell" style="width: 70px; text-align: center;">{{ order.singleWeight }}</td>
            <td class="info-cell" style="width: 70px; text-align: center; font-weight: bold; color: #2c3e50;">{{ order.totalWeight }}</td>
            <td class="info-cell" style="width: 70px; text-align: center;font-weight: bold; color: #4a6fa5;">{{ order.equipmentType }}</td>
            
            <td 
              v-for="date in dateRange" 
              :key="date.getTime()"
              class="process-cell"
              :class="{ 'today-cell': isToday(date) }"
            >
              <div class="process-container">
                <div 
                  v-for="(process, index) in processes" 
                  :key="index"
                  v-show="process.visible" 
                  class="process-bar"
                  :class="getProcessClass(process)"
                  :style="getProcessStyle(order, process, date)"
                  :title="getProcessTooltip(order, process, date)"
                >
                  {{ getProcessValue(order, process, date) }}
                </div>
              </div>
            </td>
          </tr>
          <tr v-if="filteredOrders.length === 0">
            <td :colspan="dateRange.length + (showSingleWeight ? 8 : 7)" class="empty-state">
              <i class="fas fa-inbox"></i>
              <h3>暂无订单数据</h3>
              <p>没有找到符合筛选条件的订单</p>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 编辑对话框 -->
    <div v-if="editingOrder" class="dialog-overlay">
      <div class="edit-dialog">
        <button class="close-dialog" @click="closeDialog">
          <i class="fas fa-times"></i>
        </button>
        <h2><i class="fas fa-edit"></i> 编辑订单: {{ editingOrder.id }}</h2>
        
        <div 
          v-for="(process, index) in processes" 
          :key="index"
          class="process-form"
          :style="{ '--process-color': process.color }"
        >
          <h3><i :class="process.icon"></i> {{ process.name }}</h3>
          <div class="form-row">
            <div class="form-group">
              <label><i class="fas fa-calendar-start"></i> 开始日期:</label>
              <input 
                type="date" 
                v-model="editingOrder.processes[process.key].startDate"
                :min="getMinStartDate(process, index)"
                @change="updateProcessDates(process, index)"
              >
            </div>
            <div class="form-group">
              <label><i class="fas fa-hourglass-half"></i> 持续天数:</label>
              <input 
                type="number" 
                v-model="editingOrder.processes[process.key].duration"
                min="1"
                max="10"
                @change="updateProcessDuration(process, index)"
              >
            </div>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label><i class="fas fa-weight-hanging"></i> 单日投入量 (kg):</label>
              <input 
                type="number" 
                v-model="editingOrder.processes[process.key].dailyInput"
                min="100"
                step="100"
                @change="updateHydrogenBreakingDailyInput(process, index)"
              >
            </div>
            <div class="form-group">
              <label><i class="fas fa-calendar-day"></i> 结束日期:</label>
              <div class="duration-display">
                {{ getEndDate(editingOrder.processes[process.key]) || '未设置' }}
              </div>
            </div>
          </div>
        </div>
        
        <div class="form-row" style="margin-bottom: 20px;">
          <div class="form-group">
            <label><i class="fas fa-barcode"></i> 产品代码:</label>
            <input 
              type="text" 
              v-model="editingOrder.productCode"
            >
          </div>
          <div class="form-group">
            <label><i class="fas fa-cube"></i> 毛坯尺寸:</label>
            <input 
              type="text" 
              v-model="editingOrder.blankSize"
            >
          </div>
        </div>
        <div class="form-row" style="margin-bottom: 20px;">
          <div class="form-group">
            <label><i class="fas fa-list-check"></i> 计划数量:</label>
            <input 
              type="number" 
              v-model="editingOrder.planQuantity"
              min="1"
            >
          </div>
          <div class="form-group">
            <label><i class="fas fa-weight"></i> 产品单重 (kg):</label>
            <input 
              type="number" 
              v-model="editingOrder.singleWeight"
              min="0.1"
              step="0.1"
            >
          </div>
          <div class="form-group">
            <label><i class="fas fa-industry"></i> 设备类型:</label>
            <select v-model="editingOrder.equipmentType">
              <option value="半">半自动</option>
              <option value="全">全自动</option>
            </select>
          </div>
        </div>
        <div class="form-row" style="margin-bottom: 20px;">
          <div class="form-group">
            <label><i class="fas fa-scale-balanced"></i> 订单总重 (kg):</label>
            <div class="duration-display" style="border-color: #1a936f; background-color: rgba(26, 147, 111, 0.1); color: #1a936f;">
              {{ editingOrder.totalWeight || '计算中...' }}
            </div>
          </div>
        </div>
        
        <div class="dialog-buttons">
          <button class="save-btn" @click="saveOrder">
            <i class="fas fa-save"></i> 保存
          </button>
          <button class="cancel-btn" @click="closeDialog">
            <i class="fas fa-times"></i> 取消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { debounce } from 'lodash';
export default {
  name: 'ProductionGantt',
  data() {
    return {
      processes: [
        { key: 'smelting', name: '冶炼', color: '#FF0000', icon: 'fas fa-fire', visible: true },
        { key: 'hydrogenBreaking', name: '氢破', color: '#003333', icon: 'fas fa-atom', visible: true },
        { key: 'jetMilling', name: '气流磨', color: '#996633', icon: 'fas fa-wind', visible: true },
        { key: 'pressing', name: '压型', color: '#6A0572', icon: 'fas fa-compress-arrows-alt', visible: true },
        { key: 'sintering', name: '烧结', color: '#009933', icon: 'fas fa-thermometer-full', visible: true }
      ],
      orders: [
        {
          id: 'ORD-2023-001',
          productCode: 'N52-202306',
          blankSize: 'φ10x5mm',
          planQuantity: 3000,
          singleWeight: 1.5,
          totalWeight: 4500,
          equipmentType: '半',
          processes: {
            smelting: { startDate: '2023-06-01', dailyInput: 1200, duration: 4 },
            hydrogenBreaking: { startDate: '2023-06-05', dailyInput: 1200, duration: 4 },
            jetMilling: { startDate: '2023-06-09', dailyInput: 800, duration: 2 },
            pressing: { startDate: '2023-06-11', dailyInput: 600, duration: 3 },
            sintering: { startDate: '2023-06-14', dailyInput: 400, duration: 4 }
          }
        },
        {
          id: 'ORD-2023-002',
          productCode: 'N48-202306',
          blankSize: 'φ8x4mm',
          planQuantity: 2133,
          singleWeight: 1.5,
          totalWeight: 3200,
          equipmentType: '全',
          processes: {
            smelting: { startDate: '2023-06-10', dailyInput: 1500, duration: 3 },
            hydrogenBreaking: { startDate: '2023-06-13', dailyInput: 1500, duration: 2 },
            jetMilling: { startDate: '2023-06-15', dailyInput: 1000, duration: 2 },
            pressing: { startDate: '2023-06-17', dailyInput: 700, duration: 3 },
            sintering: { startDate: '2023-06-20', dailyInput: 500, duration: 4 }
          }
        },
        {
          id: 'ORD-2023-003',
          productCode: 'SmCo-202306',
          blankSize: 'φ12x6mm',
          planQuantity: 1866,
          singleWeight: 1.5,
          totalWeight: 2800,
          equipmentType: '半',
          processes: {
            smelting: { startDate: '2023-06-15', dailyInput: 1800, duration: 2 },
            hydrogenBreaking: { startDate: '2023-06-17', dailyInput: 1800, duration: 2 },
            jetMilling: { startDate: '2023-06-19', dailyInput: 1200, duration: 2 },
            pressing: { startDate: '2023-06-21', dailyInput: 900, duration: 2 },
            sintering: { startDate: '2023-06-23', dailyInput: 600, duration: 3 }
          }
        }
      ],
      editingOrder: null,
      startDate: new Date(),
      isDragging: false,
      startDragX: 0,
      dragStartDate: new Date(),
      scrollAnimationId: null,
      showSingleWeight: true,
      equipmentFilter: 'all',
      todayIndex: 15,
      // 新增筛选相关数据
      productCodeFilter: '',
      productCodeList: [], // 用于存储唯一产品代码列表
      // 新增查询条件
      orderCodeFilter: '',
      productCodeFilter: '',
      debouncedHandleFilter: null
    };
  },
  created() {
    // 防抖处理
    this.debouncedHandleFilter = debounce(this.handleFilter, 300);
  },
  computed: {
    filteredOrdersCount() {
      return this.filteredOrders.length;
    },
    dateRange() {
      // 日期范围计算
      const range = [];
      const date = new Date(this.startDate);
      date.setDate(date.getDate() - this.todayIndex);
      
      for (let i = 0; i < 30; i++) {
        const newDate = new Date(date);
        range.push(newDate);
        date.setDate(date.getDate() + 1);
      }
      
      return range;
    },
    totalProcesses() {
      // 总工序数计算保
      return this.orders.length * this.processes.length;
    },
     // 修改原有过滤计算属性
    filteredOrders() {
      let filtered = this.orders;
      if (this.orderCodeFilter) {
        const code = this.orderCodeFilter.trim().toUpperCase();
        filtered = filtered.filter(order => 
          order.id.includes(code)
        );
      }
      
      // 产品代码过滤
      if (this.productCodeFilter) {
        const codes = this.productCodeFilter.split(',').map(c => c.trim().toUpperCase());
        filtered = filtered.filter(order => 
          codes.some(code => 
            order.productCode.toUpperCase().includes(code)
          )
        );
      }
      
      // 设备类型过滤
      if (this.equipmentFilter !== 'all') {
        filtered = filtered.filter(order => order.equipmentType === this.equipmentFilter);
      }
      
      // 新增产品代码过滤
      if (this.productCodeFilter) {
        const codes = this.productCodeFilter.split(',').map(code => code.trim().toUpperCase());
        filtered = filtered.filter(order => 
          codes.some(code => 
            order.productCode.toUpperCase().includes(code)
          )
        );
      }
      
      return filtered;
    }
  },
  mounted() {
    this.scrollToToday();
    this.orders = [];
    this.search_db_updatatime();
    // 监听滚动事件
    this.$refs.ganttContainer.addEventListener('scroll', this.handleScroll);
    this.productCodeList = [...new Set(this.orders.map(order => order.productCode))];
  },
  beforeDestroy() {
    // 移除滚动事件监听
    if (this.$refs.ganttContainer) {
      this.$refs.ganttContainer.removeEventListener('scroll', this.handleScroll);
    }
  },
  methods: {
    handleFilter() {
      this.$forceUpdate(); // 强制重新渲染表格
    },
    clearOrderCodeFilter() {
      this.orderCodeFilter = '';
      this.handleFilter();
    },
    clearProductCodeFilter() {
      this.productCodeFilter = '';
      this.handleFilter();
    },




    // 新增筛选方法
    handleProductCodeFilter() {
      // 可在此处添加防抖逻辑
      this.filteredOrders = [...this.filteredOrders]; // 触发重新计算
    },
    // clearProductCodeFilter() {
    //   this.productCodeFilter = '';
    //   this.handleProductCodeFilter();
    // },
    // 新增：处理滚动事件
    handleScroll() {
      const container = this.$refs.ganttContainer;
      const scrollTop = container.scrollTop;
      
      // 获取所有需要冻结的元素
      const frozenHeaders = container.querySelectorAll('.frozen-header');
      console.log("在滚动·······")
      // const frozenCells = container.querySelectorAll('.frozen-cell');
      
      // 设置固定位置
      frozenHeaders.forEach(header => {
        header.style.position = 'sticky';
        header.style.top = '100';
        header.style.zIndex = '2';
      });
      
    },
    // 新增：切换工序可见性
    toggleProcessVisibility(processKey) {
      const process = this.processes.find(p => p.key === processKey);
      if (process) {
        process.visible = !process.visible;
      }
    },
    formatCurrentTime() {
      // 时间格式化
      console.log("时间函数！！！")
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
    search_db_updatatime(){
      // 数据库查询
      console.log(this.formatCurrentTime())
      this.http.get('api/material_plan_xie/get_db_proinfo',
                          {}).then((reslut) => {
                            console.log(reslut[0])
                            console.log("reslut[0]")
                            for(let i=0;i<reslut.length;i++){
                              this.orders.push(
                                {
                                  id: reslut[i]["schedule_id"],
                                  productCode: reslut[i]["top_id"],
                                  blankSize: reslut[i]["schedule_blank_spec"],
                                  date_first_batch: reslut[i]["date_first_batch"].split(" ")[0],
                                  planQuantity: reslut[i]["product_qty"],
                                  singleWeight: reslut[i]["per_weight"],
                                  totalWeight: reslut[i]["total_weight"],
                                  equipmentType: reslut[i]["device_type"],
                                  processes: {
                                    smelting: { startDate: reslut[i]["yl_startdate"].split(" ")[0], dailyInput: reslut[i]["yl_per_in"], duration: reslut[i]["yl_dunring"] },
                                    hydrogenBreaking: { startDate: reslut[i]["qp_startdate"].split(" ")[0], dailyInput: reslut[i]["qp_per_in"], duration: reslut[i]["qp_dunring"] },
                                    jetMilling: { startDate: reslut[i]["qlm_startdate"].split(" ")[0], dailyInput: reslut[i]["qlm_per_in"], duration: reslut[i]["qlm_dunring"] },
                                    pressing: { startDate: reslut[i]["yx_startdate"].split(" ")[0], dailyInput: reslut[i]["yx_per_in"], duration: reslut[i]["yx_dunring"] },
                                    sintering: { startDate: reslut[i]["sj_startdate"].split(" ")[0], dailyInput: reslut[i]["sj_per_in"], duration: reslut[i]["sj_dunring"] }
                                  }
                                },
                              )
                            }
                            
                        }).catch((error) => {
                            console.log("失败",error)
                            // return "未更新"
                        });
    },
    toggleSingleWeight() {
      // 切换单重显示
      this.showSingleWeight = !this.showSingleWeight;
    },
    toggleSingleWeight() {
      // 切换单重显示
      this.showSingleWeight = !this.showSingleWeight;
    },
    scrollToToday() {
      // 滚动到今天
      this.$nextTick(() => {
        if (this.$refs.ganttContainer) {
          const dateColumnWidth = 70;
          const todayPosition = 15 * dateColumnWidth;
          this.$refs.ganttContainer.scrollLeft = todayPosition;
        }
      });
    },
    updateProcessDuration(process, index) {
      // 更新工序持续时间
      if (!this.editingOrder) return;
      const dailyInput = this.editingOrder.processes[process.key].dailyInput;
      this.updateAllProcessDurations();
      if (process.key === 'smelting') {
        this.editingOrder.processes.hydrogenBreaking.dailyInput = dailyInput;
      }
      this.updateSubsequentProcessDates(index);
    },
    updateHydrogenBreakingDailyInput(process, index) {
      // 更新氢破投入量
      if (!this.editingOrder) return;
      if (process.key === 'smelting') {
        this.editingOrder.processes.hydrogenBreaking.dailyInput = 
          this.editingOrder.processes[process.key].dailyInput;
      }
      this.updateAllProcessDurations();
    },
    updateAllProcessDurations() {
      // 更新所有工序持续时间
      if (!this.editingOrder) return;
      const totalWeight = this.editingOrder.totalWeight;
      for (const processKey in this.editingOrder.processes) {
        if (this.editingOrder.processes[processKey].dailyInput) {
          const dailyInput = this.editingOrder.processes[processKey].dailyInput;
          const duration = Math.ceil(totalWeight / dailyInput);
          this.editingOrder.processes[processKey].duration = duration;
        }
      }
    },
    updateProcessDates(process, index) {
      // 更新工序日期
      if (!this.editingOrder) return;
      this.updateSubsequentProcessDates(index);
    },
    updateSubsequentProcessDates(currentIndex) {
      // 更新后续工序日期
      if (!this.editingOrder) return;
      for (let i = currentIndex; i < this.processes.length - 1; i++) {
        const currentProcess = this.processes[i];
        const nextProcess = this.processes[i + 1];
        const startDate = new Date(this.editingOrder.processes[currentProcess.key].startDate);
        const duration = this.editingOrder.processes[currentProcess.key].duration || 0;
        startDate.setDate(startDate.getDate());
        if (currentProcess.key === 'smelting' && nextProcess.key === 'hydrogenBreaking') {
          startDate.setDate(startDate.getDate() + 3);
        } else if (currentProcess.key === 'hydrogenBreaking' && nextProcess.key === 'jetMilling') {
          startDate.setDate(startDate.getDate() + 2);
        } else if (currentProcess.key === 'jetMilling' && nextProcess.key === 'pressing') {
          startDate.setDate(startDate.getDate() + 1);
        } else if (currentProcess.key === 'pressing' && nextProcess.key === 'sintering') {
          startDate.setDate(startDate.getDate() + 1);
        }
        this.editingOrder.processes[nextProcess.key].startDate = 
          startDate.toISOString().split('T')[0];
      }
    },
    startDrag(e) {
      // 判断是否点击在日期列
        const isDateHeader = e.target.closest('th.date-header') !== null;
        if (!isDateHeader) return;

        // 阻止文本选中
        e.preventDefault();
        
        // 初始化拖拽参数
        this.isDragging = true;
        this.startDragX = e.clientX;
        this.dragStartDate = new Date(this.startDate);
        
        // 设置拖拽光标
        document.body.style.cursor = 'grabbing';
        
        // 绑定移动和结束事件
        document.addEventListener('mousemove', this.doDrag);
        document.addEventListener('mouseup', this.stopDrag);
    },
    doDrag(e) {
      if (!this.isDragging) return;
        
        // 计算拖拽偏移量
        const deltaX = e.clientX - this.startDragX;
        const daysDelta = Math.round(deltaX / 30); // 每50px对应一天
        
        // 更新起始日期
        const newDate = new Date(this.dragStartDate);
        newDate.setDate(newDate.getDate() - daysDelta);
        this.startDate = newDate;
        
        // 重置起始参数
        this.startDragX = e.clientX;
        this.dragStartDate = new Date(this.startDate)
    },
    stopDrag() {
      if (!this.isDragging) return;
        
        // 清理状态
        this.isDragging = false;
        document.body.style.cursor = '';
        
        // 解绑事件
        document.removeEventListener('mousemove', this.doDrag);
        document.removeEventListener('mouseup', this.stopDrag);
    },
    openEditDialog(order) {   //打开对应的订单编辑界面
      console.log("eeeeeeeeeeeeee")
      console.log(order)
      console.log(order.id)
      console.log(order["processes"])
      // order["processes"]["smelting"]["startDate"] = "2025-06-23"
      this.editingOrder = JSON.parse(JSON.stringify(order));

      this.updateAllProcessDurations();   //计算持续时间数据
    },
    closeDialog() {  //关闭订单编辑对话框
      this.editingOrder = null;
    },
    saveOrder() {   //保存订单编辑界面
      if (!this.editingOrder) return;           
      const index = this.orders.findIndex(o => o.id === this.editingOrder.id);
      console.log(index)
      console.log("this.editingOrder.id",this.editingOrder.id)
      console.log(this.editingOrder)
      if (index !== -1) {
        this.orders[index] = this.editingOrder;
        var js_data = JSON.parse(JSON.stringify(this.editingOrder))
        console.log(this.editingOrder["processes"])
        let in_db_data = {
          schedule_id : this.editingOrder["id"],
          yl_startdate : this.editingOrder["processes"]["smelting"]["startDate"],
          yl_dunring : this.editingOrder["processes"]["smelting"]["duration"],
          yl_per_in : this.editingOrder["processes"]["smelting"]["dailyInput"],
          // yl_stopdate : this.editingOrder["id"],
          qp_startdate : this.editingOrder["processes"]["hydrogenBreaking"]["startDate"],
          qp_dunring : this.editingOrder["processes"]["hydrogenBreaking"]["duration"],
          qp_per_in : this.editingOrder["processes"]["hydrogenBreaking"]["dailyInput"],
          // qp_stopdate : this.editingOrder["id"],
          qlm_startdate : this.editingOrder["processes"]["jetMilling"]["startDate"],
          qlm_dunring : this.editingOrder["processes"]["jetMilling"]["duration"],
          qlm_per_in:this.editingOrder["processes"]["jetMilling"]["dailyInput"],
          // qlm_stopdate : this.editingOrder["id"],
          yx_startdate :this.editingOrder["processes"]["pressing"]["startDate"],
          yx_dunring : this.editingOrder["processes"]["pressing"]["duration"],
          yx_per_in : this.editingOrder["processes"]["pressing"]["dailyInput"],
          // yx_stopdate : this.editingOrder["id"],
          sj_startdate : this.editingOrder["processes"]["sintering"]["startDate"],
          sj_dunring : this.editingOrder["processes"]["sintering"]["duration"],
          sj_per_in : this.editingOrder["processes"]["sintering"]["dailyInput"],
        }
        let jsonString_mes_data = JSON.stringify(in_db_data)
        this.http.get('api/material_plan_xie/get_db_order_plan',
                          {editingOrder_data:jsonString_mes_data}).then((reslut) => {
                            console.log(reslut[0])
                            console.log("reslut[0]")                            
                            
                        }).catch((error) => {
                            console.log("失败",error)
                            // return "未更新"
                        });
      } else {
        this.orders.push(this.editingOrder);
      }
      
      this.closeDialog();
    },
    formatDate(date) {
      // 格式化日期
      return `${date.getMonth() + 1}/${date.getDate()}`;
    },
    getDayOfWeek(date) {
      // 获取星期几
      const days = ['日', '一', '二', '三', '四', '五', '六'];
      return `周${days[date.getDay()]}`;
    },
    isToday(date) {
      // 判断是否是今天
      const today = new Date();
      return date.getDate() === today.getDate() && 
             date.getMonth() === today.getMonth() && 
             date.getFullYear() === today.getFullYear();
    },
    getProcessStyle(order, process, date) {
      // 获取工序样式
      const processData = order.processes[process.key];
      if (!processData || !processData.startDate || !processData.duration) return {};
      const startDate = new Date(processData.startDate);
      const endDate = new Date(startDate);
      endDate.setDate(endDate.getDate() + parseInt(processData.duration) - 1);
      const displayDate = new Date(date);
      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(0, 0, 0, 0);
      displayDate.setHours(0, 0, 0, 0);
      if (displayDate >= startDate && displayDate <= endDate) {
        return {
          backgroundColor: process.color,
          opacity: displayDate.getTime() === startDate.getTime() ? 1 : 0.8
        };
      }
      return {};
    },
    getProcessValue(order, process, date) {
      // 获取工序值
      const processData = order.processes[process.key];
      if (!processData || !processData.dailyInput) return '';

      const startDate = new Date(processData.startDate);
      const endDate = new Date(startDate);
      endDate.setDate(endDate.getDate() + parseInt(processData.duration) - 1);
      const displayDate = new Date(date);

      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(0, 0, 0, 0);
      displayDate.setHours(0, 0, 0, 0);

      if (displayDate >= startDate && displayDate <= endDate) {
        // 判断是否为最后一天
        if (displayDate.getTime() === endDate.getTime()) {
          // 计算剩余量 = 订单总重 - (单日投入量 × (持续天数 - 1))
          const totalWeight = order.totalWeight;
          const dailyInput = processData.dailyInput;
          const duration = parseInt(processData.duration);
          const remaining = totalWeight - dailyInput * (duration - 1);
          
          // 确保剩余量不为负数
          return remaining > 0 ? remaining.toFixed(1) : 0;
        } else {
          // 非最后一天显示正常投入量
          return processData.dailyInput;
        }
      }
      return '';
    },
    getProcessTooltip(order, process, date) {
      // 获取工序提示
      const processData = order.processes[process.key];
      if (!processData || !processData.startDate || !processData.duration) return '';

      const startDate = new Date(processData.startDate);
      const duration = parseInt(processData.duration);
      const endDate = new Date(startDate);
      endDate.setDate(endDate.getDate() + duration - 1);
      const displayDate = new Date(date);

      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(0, 0, 0, 0);
      displayDate.setHours(0, 0, 0, 0);

      if (displayDate >= startDate && displayDate <= endDate) {
        const dayOfProcess = Math.floor((displayDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
        
        // 最后一天显示剩余量
        if (displayDate.getTime() === endDate.getTime()) {
          const totalWeight = order.totalWeight;
          const dailyInput = processData.dailyInput;
          const remaining = totalWeight - dailyInput * (duration - 1);
          const displayRemaining = remaining > 0 ? remaining : 0;
          
          return `${process.name}: 第${dayOfProcess}天/${duration}天\n剩余量: ${displayRemaining}kg`;
        } else {
          // 非最后天显示正常投入量
          return `${process.name}: 第${dayOfProcess}天/${duration}天\n投入量: ${processData.dailyInput}kg`;
        }
      }
      return '';
    },
    compute_jihua_paig(){
      //查数据库单号的每日投入量、开始日期、结束日期；判断当天日期，开始和结束日期是算工序的计划量，如果
    },
    getProcessClass(process) {
      // 获取工序类
      return `process-${process.key}`;
    },
    getMinStartDate(process, index) {
      // 获取最小开始日期
      if (index === 0 || !this.editingOrder) return null;
      const prevProcess = this.processes[index - 1];
      const prevData = this.editingOrder.processes[prevProcess.key];
      if (!prevData || !prevData.startDate || !prevData.duration) return null;
      const minDate = new Date(prevData.startDate);
      minDate.setDate(minDate.getDate() + parseInt(prevData.duration));
      return minDate.toISOString().split('T')[0];
    },
    getEndDate(processData) {
      // 获取结束日期
      if (!processData.startDate || !processData.duration) return null;
      const start = new Date(processData.startDate);
      const end = new Date(start);
      end.setDate(end.getDate() + parseInt(processData.duration) - 1);
      return end.toISOString().split('T')[0];
    }
  }
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
}

/* 新增查询区域样式 */
.search-group {
  display: flex;
  gap: 8px;
  align-items: center;
  /* margin-bottom: 5px; */
}

.search-item {
  display: flex;
  gap: 8px;
  align-items: center;
  flex: 1;
  min-width: 50px;
}

.search-input {
  padding: 6px 10px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  flex: 1;
  min-width: 50px;
}

.search-clear {
  background: none;
  border: none;
  color: #6c757d;
  cursor: pointer;
  padding: 4px;
  font-size: 1.1rem;
}

.search-clear:hover {
  color: #495057;
}

/* 新增筛选控件样式 */
.product-code-filter {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-left: 5px;
}
.filter-input {
  padding: 6px 5px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  flex: 1;
  min-width: 50px;
}
.clear-filter {
  background: none;
  border: none;
  color: #6c757d;
  cursor: pointer;
  padding: 4px;
  font-size: 1.1rem;
}
.clear-filter:hover {
  color: #495057;
}
/* 新增：头部容器样式 */
.header-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  margin-bottom: 5px;
}
/* 新增：隐藏的图例项样式 */
.legend-hidden {
  opacity: 0.5;
  text-decoration: line-through;
}

.gantt-container {
  width: 100%;
  margin: 0 auto;
  background: rgba(255, 255, 255, 0.95);
  padding: 5px;
}

.controls {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
  min-width: 300px; /* 确保最小宽度 */
}

.equipment-filter {
  display: flex;
  align-items: center;
  gap: 10px;
  background: #f5f7fa;
  padding: 8px 15px;
  border-radius: 6px;
}

.equipment-filter label {
  font-weight: 600;
  color: #2c3e50;
  font-size: 0.9rem;
}

.equipment-filter select {
  padding: 5px 10px;
  border-radius: 5px;
  border: 1px solid #ced4da;
  background: white;
  min-width: 50px;
}

.search-clear {
  padding: 8px 15px;
  border: 1px solid #ec0606;
  border-radius: 6px;
  background: #ff0303;
  color: rgb(255, 0, 0);
  cursor: pointer;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.toggle-weight-btn {
  padding: 8px 15px;
  border: 1px solid #4a6fa5;
  border-radius: 6px;
  background: #4a6fa5;
  color: white;
  cursor: pointer;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.toggle-weight-btn:hover {
  background: #3a5f95;
  transform: translateY(-2px);
}

.legend {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: flex-end;
  flex: 1;
  min-width: 400px;
}
.legend-count {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.9rem;
  color: #2c3e50;
  font-weight: 600;
  padding: 4px 8px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  margin-bottom: 15px;
}
.count-badge {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #4a6fa5;
  color: white;
  font-size: 0.8rem;
  font-weight: bold;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  background: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9rem;
  border: 1px solid #e0e0e0;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 3px;
}

.gantt-table-container {
  overflow-x: auto;
  max-height: 70vh;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: white;
  margin-bottom: 15px;
  cursor: grab;
  user-select: none;
  width: 100%;
}

.gantt-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 1100px;
}

th, td {
  border: 1px solid #e0e0e0;
  text-align: center;
  padding: 8px 10px;
  font-size: 0.9rem;
}

.order-header {
  background: linear-gradient(to bottom, #2c3e50, #1a2a6c);
  color: white;
  position: absolute;
  display: grid;            /* 启用 Grid */
  place-items: center;
  z-index: 10;
  height: 90px;
  min-width: 130px;
  box-shadow: 2px 0 3px rgba(0, 0, 0, 0);
  font-size: 1rem;
}

.info-header {
  background: linear-gradient(to bottom, #4a6fa5, #2c3e50);
  color: white;
  font-size: 0.85rem;
  white-space: normal;
}

.date-header {
  background: linear-gradient(to bottom, #f8f9fa, #e9ecef);
  min-width: 70px;
  font-weight: 600;
  color: #495057;
  position: relative;
}

.frozen-header {
  position: sticky;
  top: 0;
  z-index: 1;
}

.frozen-cell {
  position: sticky;
  top: 41px; /* 表头高度 */
  z-index: 4;
}

.today-header {
  background: linear-gradient(to bottom, #ffd166, #ffb347);
  color: #2c3e50;
  font-weight: 700;
  position: relative;
}

.today-header::after {
  content: "今天";
  position: absolute;
  top: 2px;
  right: 2px;
  font-size: 0.6rem;
  background: #ef476f;
  color: white;
  padding: 1px 4px;
  border-radius: 4px;
}

.order-cell {
  background: linear-gradient(to right, #e9ecef, #d8e2dc);
  cursor: pointer;
  position: sticky;
  left: 0;
  z-index: 2;
  font-weight: 700;
  min-width: 130px;
  box-shadow: 2px 0 3px rgba(0, 0, 0, 0.08);
}

.info-cell {
  background: #ffffff;
  /* position: sticky; */
  left: 50px;
  z-index: 4;
}

.wrap-text {
  white-space: normal;
  word-break: break-word;
  line-height: 1.4;
}

.edit-icon {
  margin-left: 8px;
  color: #4a6fa5;
  transition: all 0.3s;
  font-size: 0.9rem;
}

.order-cell:hover .edit-icon {
  color: #ef476f;
  transform: rotate(15deg);
}

.process-cell {
  padding: 0;
  height: 50px;
  position: relative;
  background: repeating-linear-gradient(
    45deg,
    #f8f9fa,
    #f8f9fa 8px,
    #f0f2f5 8px,
    #f0f2f5 16px
  );
}

.today-cell {
  background: repeating-linear-gradient(
    45deg,
    #fff8e1,
    #fff8e1 8px,
    #ffecb3 8px,
    #ffecb3 16px
  );
}

.process-container {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  padding: 2px;
  gap: 2px;
}

.process-bar {
  width: 100%;
  height: 20px;
  border-radius: 3px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1rem;
  font-weight: bold;
  color: white;
  padding: 1px;
  opacity: 0.9;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.edit-dialog {
  background: white;
  border-radius: 12px;
  padding: 20px;
  width: 95%;
  max-width: 850px;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
}

.edit-dialog h2 {
  color: #2c3e50;
  margin-bottom: 15px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e9ecef;
  font-size: 1.5rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.process-form {
  background: white;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  border-left: 3px solid var(--process-color);
}

.process-form h3 {
  margin-top: 0;
  margin-bottom: 12px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1.3rem;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 12px;
}

.form-group {
  flex: 1;
  min-width: 220px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 600;
  color: #495057;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 1.1rem;
}

.form-group input, .form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ced4da;
  border-radius: 6px;
  font-size: 1.1rem;
}

.duration-display {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 6px;
  font-weight: 600;
  color: #495057;
  border: 1px dashed #ced4da;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e9ecef;
}

.dialog-buttons button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.9rem;
}

.dialog-buttons .save-btn {
  background: #1a936f;
  color: white;
}

.dialog-buttons .cancel-btn {
  background: #6c757d;
  color: white;
}

.close-dialog {
  position: absolute;
  top: 15px;
  right: 15px;
  background: none;
  border: none;
  font-size: 1.3rem;
  color: #6c757d;
  cursor: pointer;
}

.empty-state {
  text-align: center;
  padding: 30px;
  color: #6c757d;
}

.empty-state i {
  font-size: 2.5rem;
  margin-bottom: 12px;
  color: #ced4da;
}
</style>  